/**
 * 
 */
package com.javass.jdbc.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.mybatis.generator.internal.util.StringUtility;

import com.javass.jdbc.DatabaseComment;

/**
 * @author zhuguojie，zhu915139481@126.com
 * @date 2015年11月11日 下午4:35:25
 * @version 1.0
 */
public class MysqlDatabaseComment extends AbstractDatabaseComment implements DatabaseComment {

	public MysqlDatabaseComment(Connection connection) {
		super(connection);
		// TODO Auto-generated constructor stub
	}

	@Override
	public String getTableComment(String catalog, String schema, String tableName) throws SQLException {
		String comment = super.getTableComment(catalog, null, tableName);
		if (!StringUtility.stringHasValue(comment)) {
			PreparedStatement ps = null;

			ps = connection
					.prepareStatement("SELECT table_name,table_comment FROM information_schema.TABLES WHERE TABLE_SCHEMA = ? and table_name = ?");
			ps.setString(1, catalog);
			ps.setString(2, tableName);

			ResultSet resultSet = ps.executeQuery();
			if (resultSet.next()) {
				comment = resultSet.getString(2);
			}
			resultSet.close();
			ps.close();
		}
		closeConnection();
		return comment;
	}

	@Override
	public String getColumnComment(String catalog, String schema, String tableName, String columnName) throws SQLException {
		String comment = super.getColumnComment(catalog, null, tableName, columnName);
		if (!StringUtility.stringHasValue(comment)) {
			PreparedStatement ps = null;

			ps = connection
					.prepareStatement("SELECT table_name,column_name,column_comment FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = ? and table_name = ? and column_name = ?");
			ps.setString(1, catalog);
			ps.setString(2, tableName);
			ps.setString(3, columnName);

			ResultSet resultSet = ps.executeQuery();
			if (resultSet.next()) {
				comment = resultSet.getString(3);
			}
			resultSet.close();
			ps.close();
		}
		closeConnection();
		return comment;
	}
}
